/* eslint-disable no-unneeded-ternary */
import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, message, Table} from 'antd';
import routes from './routes';
import {PAGE, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {uuid} from '../utils';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import styles from './style.css';
import {validateAdd} from './utils';
import Return from '../common/Return';
import TextInput from 'Shared/components/TextInput';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import WrappedSelect from '../common/WrappedSelect';
import {isYesNo} from '../Enum';
const FormItem = Form.Item;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: [],
    };

    componentDidMount() {
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
    }

    onSubmit = () => {
        const result = validateAdd(this.state.data);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit(this.state.data).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };


    onClickAdd= () => {
        const tmp = this.state.data.concat({
            id: uuid(),
        });
        this.setState({
            hasOperat: true,
            data: tmp
        });
    }


    onDelete = e => {
        const {id} = e.target.dataset;
        const tmp = this.state.data.filter(order => order.id !== id);
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }

    onDeleteAll = () => {
        this.setState({
            hasOperat: true,
            data: [],
        });
    }


    onSelectMode = (data = {}, id) => {
        if(!id) return;
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    productCategoryId: data.id,
                    productCategoryCode: data.code,
                    productCategoryName: data.name,
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }

    onBlurCode = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    code: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onBlurName = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    name: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onBlurEnglishName = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    englishName: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onBlurRemark = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    remark: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onBlurEnglishRemark = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    englishRemark: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onBlurLaborHour = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    laborHour: value
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }
    onChange = (value, id) => {
        const tmp = this.state.data.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    isCustomed: value === 1 ? true : false
                };
            return order;
        });
        this.setState({
            data: tmp,
            hasOperat: true
        });
    }

    render() {
        const {data = []} = this.state;
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.code',
                    defaultMessage: '工位编号'
                }),
                dataIndex: 'code',
                render: (text, record) =>
                    <FormItem validateStatus={this.state.isValidate && !record.code ? 'error' : null}
                        required>
                        <TextInput id={record.id}
                            value={record.code} onBlur={this.onBlurCode} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.name',
                    defaultMessage: '工位名称'
                }),
                dataIndex: 'name',
                render: (text, record) =>
                    <FormItem validateStatus={this.state.isValidate && !record.name ? 'error' : null}
                        required>
                        <TextInput id={record.id}
                            value={record.name} onBlur={this.onBlurName} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.englishName',
                    defaultMessage: '英文名称'
                }),
                dataIndex: 'englishName',
                render: (text, record) =>
                    <FormItem validateStatus={this.state.isValidate && !record.englishName ? 'error' : null}
                        required>
                        <TextInput id={record.id}
                            value={record.englishName} onBlur={this.onBlurEnglishName} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.productCategoryId',
                    defaultMessage: '车型分类'
                }),
                dataIndex: 'productCategoryId',
                width: 250,
                render: (text, record) => {
                    const {productCategoryId, productCategoryCode, productCategoryName} = record;
                    const value = productCategoryId ? {
                        id: productCategoryId,
                        code: productCategoryCode,
                        name: productCategoryName,
                    } : null;
                    return (<FormItem>
                        <ProductCategorySelectPanel
                            value={value}
                            id={record.id}
                            onSelect={this.onSelectMode} />
                    </FormItem>);
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.laborHour',
                    defaultMessage: '工时'
                }),
                dataIndex: 'laborHour',
                render: (text, record) =>
                    <FormItem validateStatus={this.state.isValidate && !record.laborHour ? 'error' : null}
                        required>
                        <LocalizeInputNumber id={record.id}
                            value={record.laborHour} onBlur={this.onBlurLaborHour} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.isCustomed',
                    defaultMessage: '是否自定义'
                }),
                dataIndex: 'isCustomed',
                render: (text, record) =>
                    <FormItem validateStatus={this.state.isValidate && !record.isCustomed ? 'error' : null}
                        required>
                        <WrappedSelect
                            id={record.id}
                            allowClear
                            value={record.isCustomed ? 1 : 0}
                            options={isYesNo.toList()}
                            onChange={this.onChange} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
                render: (text, record) =>
                    <FormItem>
                        <TextInput id={record.id}
                            value={record.remark} onBlur={this.onBlurRemark} />
                    </FormItem>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.englishRemark',
                    defaultMessage: '英文备注'
                }),
                dataIndex: 'englishRemark',
                render: (text, record) =>
                    <FormItem>
                        <TextInput id={record.id}
                            value={record.englishRemark} onBlur={this.onBlurEnglishRemark} />
                    </FormItem>
            },
            {
                title: data.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDelete} key="delete" data-id={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];

        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card title={this.props.intl.formatMessage({
                            id: 'add.workItem.add.title',
                            defaultMessage: '工位'
                        })}
                        extra={<Button onClick={this.onClickAdd} size="small">
                            {this.props.intl.formatMessage({
                                id: 'add.btn.add',
                                defaultMessage: '新增'
                            })}
                        </Button>}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={data}
                                {...TABLE} />
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    onClickAddWorkItem,
    tableSearch,
} from './actions';
import {createSelector} from 'reselect';
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    permissions => {
        const data = permissions.toJS();
        return data.includes(PERMISSION.add);
    }
);
const mapStateToProps = state => ({
    submitable: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onSubmit: data => dispatch(onClickAddWorkItem(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    }),
    onCancel: () => {
        ownProps.history.goBack();
    },
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
